package org.dreamland.infrastructure.security

import com.google.code.kaptcha.Producer
import com.google.common.cache.Cache
import com.google.common.cache.CacheBuilder
import org.springframework.stereotype.Component
import java.io.ByteArrayOutputStream
import java.util.*
import java.util.concurrent.TimeUnit
import javax.imageio.ImageIO

@Component
class GraphicCaptchaManager(
        private val producer: Producer
) {

    private val captchaStore: Cache<String, String> = CacheBuilder.newBuilder()
            .maximumSize(10000)
            .expireAfterWrite(1000, TimeUnit.SECONDS)
            .build()

    private val captchaImageType = "png"

    fun captchaBase64Code(captchaKey: String, expirationTime: Long = 60*60* 1000): String {
        val captchaText = producer.createText()
        val captchaImage = producer.createImage(captchaText)

        captchaStore.put(captchaKey, captchaText)
        val outputStream = ByteArrayOutputStream()
        ImageIO.write(captchaImage, captchaImageType, outputStream)
        return Base64.getEncoder().encodeToString(outputStream.toByteArray())
    }

    fun matches(captchaKey: String, code: String): Boolean {
        val existedCode: String = captchaStore.getIfPresent(captchaKey) as String
        return code == existedCode
    }
}